<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
      :before-close="handleClose"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="150px"
      >
        <el-form-item label="专栏标题" prop="bookName">
          <el-input v-model="dataForm.bookName" placeholder="" maxLength="14"></el-input>
          <div style="color: #999;font-size: 12px;">最多14个字</div>
        </el-form-item>
        <el-form-item label="专栏作者" prop="author">
          <el-input v-model.number="dataForm.author" maxLength="7" autocomplete="off"></el-input>
          <div style="color: #999;font-size: 12px;">最多7个字</div>
        </el-form-item>
        <el-form-item label="作者简介" prop="speaker">
          <el-input v-model.number="dataForm.speaker" maxLength="20" placeholder="一句话介绍作者" autocomplete="off"></el-input>
          <div style="color: #999;font-size: 12px;">最多20个字</div>
        </el-form-item>
        <el-form-item label="推荐文案" prop="briefIntroduction">
          <el-input v-model.number="dataForm.briefIntroduction" maxLength="50" placeholder="" autocomplete="off"></el-input>
          <div style="color: #999;font-size: 12px;">最多50个字</div>
        </el-form-item>
        <el-form-item label="封面图" prop="coverUrl">
          <el-upload
            ref="replaceUploader"
            class="upload-demo"
            :action="url"
            :before-upload="handleBefore"
            :on-success="handlePreview"
            :on-remove="handleRemovesuo"
            :file-list="fileList"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <div class="tips" style="color: #999;font-size: 12px;">上传图片的尺寸是399x525</div>
        </el-form-item>
        <el-form-item label="嘉宾简介" prop="bookDesc">
          <el-input v-model="dataForm.bookDesc" maxLength="65" type="textarea" :rows="3" placeholder=""></el-input>
          <div style="color: #999;font-size: 12px;">最多65个字</div>
        </el-form-item>
        <el-form-item label="专栏导读" class="content" prop="chapterDesc">
          <template>
            <script :id="cueId" class="ueditor-box" type="text/plain">{{dataForm.chapterDesc}}</script>
          </template>
        </el-form-item>
        <el-form-item label="视频时长" prop="video_duration">
          <el-input v-model="dataForm.video_duration" placeholder="例如: 00:40:41"></el-input>
        </el-form-item>
        <el-form-item label="上传视频" prop="sourceInfovideo_url">
          <video
            v-if="showvideo_url"
            :src="dataForm.sourceInfo.video_url"
            style="width: 185px;"
            controls="controls"
            id="myvideo"
          >您的浏览器不支持视频播放
          </video>
          <div style="color:#00f;width: 100%;overflow: hidden; " v-if="dataForm.sourceInfo.video_url!=''">
            {{dataForm.sourceInfo.video_name}}
          </div>
          <el-upload
            ref="replaceUploader1"
            :file-list="replaceList1"
            :show-file-list="true"
            :action="videourl"
            :on-success="handleVideoSuccess"
            :before-upload="beforeUploadVideo"
            :on-remove="removefile1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传mp4/video/ogg/flv/aviwmv/rmvb文件且大小不超过150M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频封面" prop="sourceInfocover_url">
          <el-upload
            ref="replaceList2"
            class="upload-demo"
            :action="uploadUrl"
            :before-upload="beforeimgUpload"
            :on-success="handleimgSuccess"
            :on-remove="removefile2"
            :file-list="replaceList2"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <div class="tips" style="color: #999;font-size: 12px;">上传图片的尺寸是16:9</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="preview()">预览</el-button>
        <el-button @click="down()">取消</el-button>
        <el-button type="primary" @click="getContent()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="qrcode" width="30%">
      <div class="qrcode">
        <img :src="qrimg">
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss">
  .ueditor-box {
    height: 150px;
    // width: 60%;
  }

  .qrcode {
    width: 200px;
    height: 200px;
    margin: 0 auto;
  }

  .qrcode img {
    width: 100%;
    height: 100%;
  }

  .content {
    height: 590px !important;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
  import ueditor from "ueditor";

  export default {
    data() {
      return {
        showvideo_url: false,
        fileList: [],
        visible: false,
        audios: false,
        objaudio: false,
        listens: true,
        qrcode: false,
        dataForm: {
          author: '',
          bookName: "",
          briefIntroduction: "",
          coverUrl: '',
          bookDesc: "",
          chapterDesc: '',
          speaker: "",
          sourceInfo: {
            audio_url: "",
            audio_name: "",
            audio_time: "",
            video_url: "",
            video_name: '',
            cover_url: '',//视频封面URL
            cover_name: '',
          },
        },
        dataRule: {
          bookName: [
            {required: true, message: "专栏标题不能为空", trigger: "blur"}
          ],
          author: [
            {required: true, message: "专栏作者不能为空", trigger: "blur"},
          ],
          bookDesc: [
            {required: true, message: "嘉宾简介不能为空", trigger: "blur"},
          ],
          briefIntroduction: [
            {required: true, message: "推荐文案不能为空", trigger: "blur"},
          ],
          speaker: [
            {required: true, message: "作者简介不能为空", trigger: "blur"},
          ],
          sourceInfovideo_url: [
            {required: true, message: "视频不能为空", trigger: "blur"},
          ],
          coverUrl: [
            {required: true, message: "封面图不能为空", trigger: "blur"},
          ],
          chapterDesc: [
            {required: true, message: "专栏导读不能为空", trigger: "blur"},
          ],
          sourceInfocover_url: [
            {required: true, message: "视频封面不能为空", trigger: "blur"},
          ],
          video_duration: [
            {required: true, message: "视频时长不能为空", trigger: "blur"},
            {
              pattern: /\d{2}:\d{2}:\d{2}/,
              message: "请输入正确格式",
              trigger: "blur"
            }
          ]
        },
        url: "",
        ue: null,
        cueId: `J_ueditorBox_${new Date().getTime()}`,
        ueContent: "",
        replaceList: [],
        replaceList1: [],
        replaceList2: [],
        qrimg: "", //二维码
        getQr: "",
        videourl: "", //视频url
        imageUrl: '',//图片路径
        hasVideo: "",//判断是否有视频
        uploadUrl: "",//上传图地址
      };
    },
    mounted() {
      this.url = this.$http.adornUrl(
        `/course/bookchapter/upload?token=${this.$cookie.get("token")}`
      );
      this.videourl = this.$http.adornUrl(
        `/course/bookchapter/uploadVideo?token=${this.$cookie.get("token")}`
      );
      this.uploadUrl = this.$http.adornUrl(
        `/course/bookchapter/uploadVideoCover?token=${this.$cookie.get("token")}`
      );
    },
    methods: {
      handlePreview(response, file, fileList,) {
        if (response && response.code === 0) {
          this.dataForm.coverUrl = response.url
          if(fileList.length>0) {
            this.fileList = [fileList[fileList.length-1]]
          }
        } else {
          this.$message.error(response.msg)
        }
      },
      handleRemovesuo() {
        this.dataForm.coverUrl = ''
      },
      handleBefore(file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error('上传封面只能是图片!')
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 399;
          let height = 525;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的图片必须是399x525!");
            return Promise.reject();
          }
        );
        const is250K = file.size / 1024 < 250
        if (!is250K) {
          this.$message.error('上传的图片要小于250KB!')
        }
        return isJPG && is250K && isSize
      },
      // 关闭窗口音频就关闭
      handleClose() {
        let that = this;
        this.visible = false;
        var myAuto =
          document.getElementById("myaudio");

        console.log(this.dataForm.sourceInfo.coverUrl)
        // var myvideo =  document.getElementById("myvideo")
        if (myAuto) {
          myAuto.pause();
          myAuto.load();
          that.ue.execCommand("cleardoc");
        } else {
          that.ue.execCommand("cleardoc");
        }
      },
      // 预览
      preview() {
        this.ue.ready(() => {
          this.ueContent = this.ue.getContent();
        });
        this.getQr = this.ueContent.replace(
          /<img/g,
          "<img style='width:100%;height:auto'"
        );
        let audio = ''
        let video = ''
        if (this.dataForm.sourceInfo.video_url) {
          video = `<div><video
            src="${this.dataForm.sourceInfo.video_url}"
            poster="${this.dataForm.sourceInfo.cover_url}"
            style="width: 100%;"
            controls="controls"
          ></video></div>`
        }
        if (this.dataForm.sourceInfo.audio_url) {
          audio = `<div><div style="position: fixed;width: 100%;height: 120px;top: 0;left: 0;background: #fff;z-index:99;">
<div style="display: flex;">
<div class="btn" style="font-size: 12px;margin: 10px;width: 35px;height: 35px;border-radius: 50px;border: 1px solid #efefef;text-align: center;line-height: 35px;background: #17B3A3;color: #fff;" onclick="setspeed(this,1)">1倍</div>
<div class="btn" style="font-size: 12px;margin: 10px;width: 35px;height: 35px;border-radius: 50px;border: 1px solid #efefef;text-align: center;line-height: 35px;" onclick="setspeed(this,1.5)">1.5倍</div>
<div class="btn" style="font-size: 12px;margin: 10px;width: 35px;height: 35px;border-radius: 50px;border: 1px solid #efefef;text-align: center;line-height: 35px;" onclick="setspeed(this,2)">2倍</div></div>
<audio id="audiodom" controls="controls" style="width: 100%;" src="${this.dataForm.sourceInfo.audio_url}" />
</div>
<div style="margin-top: 130px;"></div>`
        }
        let script = `\<script\>
function setspeed(self,speed){
let btn = document.getElementsByClassName('btn')
for(let i=0;i<btn.length;i++){
btn[i].style.background='#fff'
btn[i].style.color='#000'
}
self.style.background = '#17B3A3'
self.style.color = '#fff'
document.getElementById('audiodom').playbackRate = speed
}
\<\/script\>`
        this.$http({
          url: this.$http.adornUrl("/course/bookchapter/getQr"),
          method: "post",
          data: this.$http.adornData({
            content: audio + video + this.getQr + script
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.qrcode = true;
            this.qrimg = data.qrUrl;
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      // 取消按钮音频就关闭并且富文本清空
      down() {
        let that = this;
        this.visible = false;
        var myAuto = document.getElementById("myaudio");
        this.dataForm.sourceInfo.coverUrl = "";
        // var myvideo =  document.getElementById("myvideo")[0]
        if (myAuto) {
          myAuto.pause();
          myAuto.load();
          // myvideo.pause();
          that.ue.execCommand("cleardoc");
          this.objaudio = false;
        } else {
          that.ue.execCommand("cleardoc");
          this.objaudio = false;
        }
      },
      listen() {
        this.objaudio = true;
      },
      // 移除音频
      removefile() {
        this.dataForm.sourceInfo.audio_url = "";
      },
      removefile1() {
        this.showvideo_url = false
        this.dataForm.sourceInfo.video_url = "";
      },
      removefile2() {
        this.dataForm.sourceInfo.cover_url = "";
      },
      init(data) {
        this.visible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          this.$refs.replaceUploader.clearFiles();
          this.$refs.replaceUploader1.clearFiles();
          this.$refs.replaceList2.clearFiles();
          this.showvideo_url = false
          if (data) {
            this.showvideo_url = true
            this.dataForm = {...data}
            this.fileList = data.coverUrl?[{name: '封面图', url: data.coverUrl}]:[]
            this.replaceList2 = JSON.parse(data.sourceInfo).cover_url?[{name: '视频封面', url: JSON.parse(data.sourceInfo).cover_url}]:[]
            this.dataForm.sourceInfocover_url = JSON.parse(data.sourceInfo).cover_url
            this.dataForm.sourceInfo = JSON.parse(this.dataForm.sourceInfo);
            this.dataForm.sourceInfovideo_url = this.dataForm.sourceInfo.video_url
            if (this.dataForm.sourceInfo && this.dataForm.sourceInfo.video_duration) {
              const duration = this.dataForm.sourceInfo.video_duration / 1000
              const hour = parseInt(duration / 3600) < 10 ? '0' + parseInt(duration / 3600) : parseInt(duration / 3600)
              const minute = parseInt(duration % 3600 / 60) < 10 ? '0' + parseInt(duration % 3600 / 60) : parseInt(duration % 3600 / 60)
              const second = parseInt(duration % 60) < 10 ? '0' + parseInt(duration % 60) : parseInt(duration % 60)
              this.dataForm.video_duration = `${hour}:${minute}:${second}`
            }
            this.dataForm.chapterDesc = data.chapterDesc;
            setTimeout(()=> {
              this.ue = ueditor.getEditor(this.cueId, {
                // serverUrl: '', // 服务器统一请求接口路径
                zIndex: 3000
              });
              this.ue.ready(() => {
                this.ue.setContent(this.dataForm.chapterDesc);
              });
            },200)
          } else {
            this.dataForm = {}
            this.dataForm.sourceInfo = {}
            this.dataForm.bookType = 3
            setTimeout(()=> {
              this.ue = ueditor.getEditor(this.cueId, {
                // serverUrl: '', // 服务器统一请求接口路径
                zIndex: 3000
              });
            },200)
          }
        })
      },
      handleAvatarSuccess(response, file, fileList) {
        this.replaceList = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          this.dataForm.sourceInfo.audio_url = response.url;
          this.dataForm.sourceInfo.audio_name = file.name;
          this.audios = true;
          this.objaudio = false;
          this.listens = false;
        } else {
          this.$message.error(response.msg);
        }
      }
      ,
      // 上传音频
      beforeAvatarUpload(file) {
        this.objaudio = false;
        var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);

        const extension = testmsg === "mp3";
        if (!extension) {
          this.$message({
            message: "上传文件只能是mp3格式！",
            type: "error"
          });
        } else {
          // 移除音频以便重新加载音频文件
          this.removefile();
        }
        return extension;
      }
      ,
      // 改变上传的时候取最后一个，实现替换上传
      handleChange(files, fileList) {
        // 获取最后一次得到的文件
        const aa = fileList[fileList.length - 1];
        // 覆盖上一次的文件
        this.replaceList = [];
        this.replaceList.push(aa);
      }
      ,
      handleChange1(files, fileList) {
        // 获取最后一次得到的文件
        if(fileList.length>0) {
          const aa = fileList[fileList.length - 1];
          // 覆盖上一次的文件
          this.replaceList1 = [];
          this.replaceList1.push(aa);
        }
      }
      ,
      handleChange2(files, fileList) {
        // 获取最后一次得到的文件
        const aa = fileList[fileList.length - 1];
        // 覆盖上一次的文件
        this.replaceList2 = [];
        this.replaceList2.push(aa);
      }
      ,
      //上传视频
      beforeUploadVideo(file) {
        this.dataForm.sourceInfo.video_size = file.size;
        const isLt50M = file.size / 1024 / 1024 > 150;
        if (
          [
            "video/mp4",
            "video/ogg",
            "video/flv",
            "video/avi",
            "video/wmv",
            "video/rmvb"
          ].indexOf(file.type) == -1
        ) {
          this.$message.error("请上传正确的视频格式");
          return false
        } else if (isLt50M) {
          this.$message.error("请上传的视频小于150M");
          return false
        } else {
          this.removefile1();
        }
      }
      ,
      //视频上传成功
      handleVideoSuccess(response, file, fileList) {
        this.replaceList1 = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          if(fileList.length>0) {
            this.replaceList1 = [fileList[fileList.length-1]]
          }
          this.showvideo_url = true
          this.dataForm.sourceInfovideo_url = response.videoUrl;
          this.dataForm.sourceInfo.video_url = response.videoUrl;
          this.dataForm.sourceInfo.video_name = response.videoName;
        } else {
          this.$message.error(response.msg);
        }
      }
      ,
      // 上传视频封面
      handleimgSuccess(res, file, fileList) {
        this.dataForm.sourceInfocover_url = res.coverUrl;
        this.dataForm.sourceInfo.cover_url = res.coverUrl;
        this.dataForm.sourceInfo.cover_name = res.coverName;
        if(fileList.length>0) {
          this.replaceList2 = [fileList[fileList.length-1]]
        }
      }
      ,
      beforeimgUpload(file) {
        const isType = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isType) {
          this.$message.error('上传封面图片只能是 png/jpg/jpeg 格式!');
        }
        const is250K = file.size / 1024 < 250
        if (!is250K) {
          this.$message.error('上传的图片要小于250KB!')
        }
        const isSize = new Promise(function (resolve, reject) {
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function () {
            let valid = Math.round(img.width / img.height) == 2;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的视频封面必须是16:9!");
            return Promise.reject();
          }
        );
        console.log(is250K && isSize)
        return is250K && isType && isSize
      }
      ,
      // 表单提交
      getContent(res, file) {
        let that = this;
        this.ue.ready(() => {
          this.ueContent = this.ue.getContent();
        });
        this.dataForm.chapterDesc = this.ueContent.replace(/<p>/g, '<p style="font-size:16px">')
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            const durationArr = this.dataForm.video_duration?this.dataForm.video_duration.split(':'): ''
            this.dataForm.sourceInfo.video_duration = durationArr[0] * 60 * 60 * 1000 + durationArr[1] * 60 * 1000 + durationArr[2] * 1000
            if (!this.dataForm.sourceInfo.video_url) {
              this.$message({
                message: '请上传视频',
                type: 'warning'
              })
              return
            }
            if(!this.dataForm.coverUrl) {
              this.$message({
                message: '请上传封面图',
                type: 'warning'
              })
              return
            }
            if (!this.dataForm.sourceInfo.cover_url) {
              this.$message({
                message: '请上传视频封面',
                type: 'warning'
              })
              return
            }
            // 获取音频时长
            // 这里加了下判断，是在修改的时候修改其他字段不改这个音频也不会报错
            if (
              document.getElementById("myaudio") ||
              document.getElementById("url")
            ) {
              this.dataForm.sourceInfo.audio_time =
                document.getElementById("myaudio").duration * 1000 ||
                document.getElementById("url").duration * 1000;
            }
            this.dataForm.sourceInfo = JSON.stringify(this.dataForm.sourceInfo)
            delete this.dataForm.sourceInfovideo_url
            delete this.dataForm.sourceInfocover_url
            delete this.dataForm.isAlive
            delete this.dataForm.gmtCreated
            delete this.dataForm.gmtUpdate
            delete this.dataForm.bookVisit
            delete this.dataForm.recommendId
            delete this.dataForm.isRecommend
            this.$http({
              url: this.$http.adornUrl(
                `/course/bookinfo/famousColumn/${!this.dataForm.id ? "save" : "update"}`
              ),
              method: "post",
              data: this.$http.adornData(this.dataForm)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
                that.ue.execCommand("cleardoc");
                this.audios = false;
              } else {
                this.$message.error(data.msg);
                this.dataForm.sourceInfo = JSON.parse(this.dataForm.sourceInfo)
              }
            });
          }
        });
      }
    }
  };
</script>
